package com.lee.nio.zerocopy;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * NewIOServer
 * 零拷贝IO服务器
 *
 * @author dralee
 * @date 2022-01-01 15:00:29
 **/
public class NewIOServer {
    public static void main(String[] args) throws IOException {
        InetSocketAddress address = new InetSocketAddress(7001);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.bind(address);
        // 创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            int read = 0;
            while (-1 != read) {
                try {
                    read = socketChannel.read(buffer);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                buffer.rewind(); // 倒带position=0 mark作废
            }
        }
    }
}
